package com.threegroup.admin.service.impl;

import com.threegroup.admin.dao.SysMenuDao;
import com.threegroup.admin.dto.SysMenuDTO;
import com.threegroup.admin.entity.SysMenuEntity;
import com.threegroup.admin.enums.SuperAdminEnum;
import com.threegroup.admin.security.user.SecurityUser;
import com.threegroup.admin.service.ISysMenuService;
import com.threegroup.common.utils.BeanCopierUtils;
import com.threegroup.common.utils.ConvertUtils;
import com.threegroup.common.utils.TreeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl implements ISysMenuService {

    @Resource
    private SysMenuDao sysMenuDao;

    /**
     * 用户菜单列表
     *
     * @param user  用户
     * @param type 菜单类型
     */
    @Override
    public List<SysMenuDTO> getUserMenuList(SecurityUser user, Integer type) {
        List<SysMenuEntity> menuList;
        //系统管理员，拥有最高权限
        if(user.getSuperAdmin() == SuperAdminEnum.YES.value()){
            menuList = sysMenuDao.getMenuList(type);
        }else {
            menuList = sysMenuDao.getUserMenuList(user.getUid(), type);
        }
        List<SysMenuDTO> dtoList = BeanCopierUtils.copyList(menuList, SysMenuDTO.class);
        return TreeUtils.build(dtoList);
    }

    /**
     * 获取权限信息
     *
     * @param user 用户
     * @return
     */
    @Override
    public Set<String> getUserPermission(SecurityUser user) {

        List<String> permissionsList;
        //系统管理员，拥有最高权限
        if(user.getSuperAdmin() == SuperAdminEnum.YES.value()){
            permissionsList = sysMenuDao.getPermissionsList();
        }else {
            permissionsList = sysMenuDao.getUserPermissionsList(user.getUid());
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String permissions : permissionsList){
            if(StringUtils.isBlank(permissions)){
                continue;
            }
            permsSet.addAll(Arrays.asList(permissions.trim().split(",")));
        }

        return permsSet;
    }
}
